# coding=utf-8

from framework.db.mysql import BaseDb
from tornado import gen
from lib import log
import time

class Index(BaseDb):

    @gen.coroutine
    def select_food(self, Fschool_id, page, offset):
        query = '''SELECT Fid, Fname, Fprice, Fimg, Fdesc 
                FROM tb_food 
                WHERE Fschool_id = %s 
                ORDER BY Fcreate_time DESC
                LIMIT %s, %s'''
        count_sql = 'SELECT count(Fid) FROM tb_food WHERE Fschool_id = %s'

        ret = yield self.executejson(query, (Fschool_id, page, offset))
        count = yield self.execute(count_sql, (Fschool_id))
        raise gen.Return((ret, count[0][0]))

    @gen.coroutine
    def select_old_food(self, Fschool_id, Fuser_id, page, offset):
        query = '''SELECT Fname, Ftext
                FROM tb_food_log 
                WHERE Fschool_id = %s 
                AND Fuser_id=%s 
                LIMIT %s, %s'''
        count_sql = 'SELECT count(Fid) FROM tb_food_log WHERE Fschool_id = %s AND Fuser_id=%s'

        ret = yield self.executejson(query, (Fschool_id, Fuser_id, page, offset))
        count = yield self.execute(count_sql, (Fschool_id, Fuser_id))
        raise gen.Return((ret, count[0][0]))

    @gen.coroutine
    def buy_food(self, data):
        query = 'SELECT sum(Fprice) FROM tb_food WHERE Fid in %s'
        text = data['Ftext']

        food_id = '('
        text = text.split('|')
        for i in text:
            food_id += i.split(':')[0] + ','
        food_id = food_id[0:-1] + ')'
        if food_id != '()':
            count = yield self.execute(query% (food_id))
            data['Fprice'] = count[0][0]

        yield self.insert("tb_food_log", data)
        self.commit()

        raise gen.Return()